/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.furb.trabalhoFinal.Utils;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Usuario
 */
public class FileManager {

  public static Boolean serializeObject(Object object){
    return serializeObject(object, object.getClass());
  }

  public static Boolean serializeObject(Object object, Class clazz){
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
      try (FileOutputStream fos = new FileOutputStream(clazz.getName())) {
        final ObjectOutputStream oos;
        try {
          oos = new ObjectOutputStream(baos);
          oos.writeObject(object);
          oos.close();
        } catch (IOException ex) {
          String xMsg = "Falha ao serializar os objetos, mensagem de erro retornada: " + ex.getMessage();
          Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE, xMsg, ex);
        }
        fos.write(baos.toByteArray());
      }
    } catch (final Exception e) {
			String xMsg = "Falha ao salvar arquivo, mensagem de erro retornada: " + e.getMessage();
      Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE, xMsg, e);
		}
    return true;
  }

  public static Object getSerializedObject(Class clazz){
    final File file = new File(clazz.getName());
		if (file.exists()){
      final byte[] buffer = new byte[(int) file.length()];
      final FileInputStream fis;
      try {
        fis = new FileInputStream(file);
        fis.read(buffer);
        fis.close();
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(buffer));
        return ois.readObject();
      } catch (ClassNotFoundException ex) {
        Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE, null, ex);
      } catch (FileNotFoundException ex) {
        Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IOException ex) {
        Logger.getLogger(FileManager.class.getName()).log(Level.SEVERE, null, ex);
      }
    }
    return null;
  }
}
